package com.atguigu.tingshu.user.logins.strategy;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.tingshu.account.client.UserAccountFeignClient;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.logins.annotation.MyLoginType;
import com.atguigu.tingshu.user.logins.util.LoginType;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import jakarta.annotation.Resource;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * title:
 * author: zgl
 * date: 2024/2/27
 * description：
 */
@MyLoginType(LoginType.WX_LOGIN)
public class WxLogin implements KindsLogin {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private WxMaService wxMaService;
    @Resource
    private UserAccountFeignClient userAccountFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private KafkaService kafkaService;

    @Override
    public Map<String, Object> login(Map<String, Object> paramMap) {
        try {
            //获取参数
            Object code = paramMap.get("code");
            //调用微信登录接口获取openId
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code.toString());
            //获取openId
            String openid = sessionInfo.getOpenid();
            //根据openId查询数据库
            UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));
            //如果不存在，创建隐式用户
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setWxOpenId(openid);
                userInfo.setNickname("飞翔的小鸟" + IdWorker.getIdStr());
                userInfo.setAvatarUrl("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2Fa4f5df9c-74df-4a6c-ac3b-5534a7626188%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1711516053&t=945c1684be29c58228fc74943c43c006");
                userInfo.setStatus("1");
                this.userInfoMapper.insert(userInfo);
                // 初始化账户(远程调用)
                //userAccountFeignClient.saveAccount(userInfo.getId());
                //使用kafka做消息队列解决分布式事务
                kafkaService.sendMsg(KafkaConstant.QUEUE_USER_REGISTER, userInfo.getId().toString());
            }
            //生成token，保存到redis，返回给客户端
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            UserInfoVo userInfoVo = new UserInfoVo();
            BeanUtils.copyProperties(userInfo, userInfoVo);
            System.out.println(userInfoVo);
            redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + token, userInfoVo);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return map;
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("微信登录失败");
    }
}
